package cn.tedu.jxc.controller;

import cn.tedu.jxc.aop.LogAnnotation;
import cn.tedu.jxc.mapper.UserMapper;
import cn.tedu.jxc.pojo.dto.TimeDTO;
import cn.tedu.jxc.pojo.dto.UserDTO;
import cn.tedu.jxc.pojo.dto.UserInsertDTO;
import cn.tedu.jxc.pojo.dto.UserUpdateDTO;
import cn.tedu.jxc.pojo.vo.RoleSelectVO;
import cn.tedu.jxc.pojo.vo.UserStandardVO;
import cn.tedu.jxc.security.LoginPrincipal;
import cn.tedu.jxc.service.UserService;
import cn.tedu.jxc.web.JsonPage;
import cn.tedu.jxc.web.JsonResult;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.net.HttpCookie;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * 用户管理
 */

@Slf4j
@Validated
@RequestMapping("/users")
@RestController
@Api(tags = "01.用户管理")
public class UserController {
    @Autowired
    UserService  userService;

    @Autowired
    UserMapper mapper;

    @ApiOperation("用户登录")
    @ApiOperationSupport(order = 50)
    @PostMapping("/login")
    public JsonResult<String> login( UserDTO userDTO,HttpServletResponse response){
        String jwt = userService.login(userDTO);
        if (userDTO.getRem()){
            Cookie c1 = new Cookie("username",userDTO.getUsername());
            Cookie c2 = new Cookie("password",userDTO.getPassword());
            c1.setMaxAge(60*60*24);
            c2.setMaxAge(60*60*24);
            c1.setPath("/");
            c2.setPath("/");
            response.addCookie(c1);
            response.addCookie(c2);
        }

        log.debug("用户登录成功!");
        return JsonResult.ok(jwt);
    }


    /**
     * 查找用户
     * @param username
     * @param page
     * @param size
     * @return
     */
    @ApiOperation("用户查找")
    @ApiOperationSupport(order = 300)
    @GetMapping("/search")
    @LogAnnotation(module = 1,operator = "通过用户名查找用户")
    public JsonResult<List<UserStandardVO>> selectByUsername(String username, int page, int size){
        int index = (page-1)*size;
        List<UserStandardVO> list = userService.search(username, index, size);
        return JsonResult.ok(list);
    }

    /**
     *手机号查找
     * @param phoneNum
     * @return
     */
    @GetMapping("/search-phone")
    @LogAnnotation(module = 1,operator = "通过手机号查找用户")
    public JsonResult<JsonPage<UserStandardVO>> selectByPhoneNum(String phoneNum,Integer page,Integer pageSize){
        PageHelper.startPage(page,pageSize);
        List<UserStandardVO> list = mapper.selectByPhoneNum(phoneNum);
        return JsonResult.ok(JsonPage.restPage(new PageInfo<>(list)));
        //TODO
    }

    /**
     *时间查找
     * @param timeDTO
     * @return
     */
    @PostMapping("/search-date")
    @LogAnnotation(module = 1,operator = "通过日期查找用户")
    public JsonResult<JsonPage<UserStandardVO>> selectByDate(TimeDTO timeDTO){
        log.debug("获取的时间为:{},{},{}",timeDTO.getDateTime(),timeDTO.getPage(),timeDTO.getPageSize());
        PageHelper.startPage(timeDTO.getPage(),timeDTO.getPageSize());
        List<UserStandardVO> list = mapper.selectByDate(timeDTO.getDateTime());
        return JsonResult.ok(JsonPage.restPage(new PageInfo<>(list)));

    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @ApiOperation("根据id删除用户")
    @ApiOperationSupport(order = 200)
    @PostMapping("/{id:[\\d]+}/deleteById")
    @PreAuthorize("hasAuthority('/admin/delete')")
    @LogAnnotation(module = 1,operator = "删除用户")
    public JsonResult<Void> deleteById(@Range(min =1,message = "输入的id有误")@PathVariable Integer id){
       userService.deleteById(id);
       return JsonResult.ok();
    }

    /**
     * 查询用户列表
     * @param page
     * @param size
     * @return
     */
    @ApiOperation("用户列表")
    @ApiOperationSupport(order = 100)
    @GetMapping("/select")
    @PreAuthorize("hasAuthority('/admin/read')")
    public JsonResult<List<UserStandardVO>> findAllUser(int page, int size){
        List<UserStandardVO> list = userService.list(page, size);
        return JsonResult.ok(list);
    }

    /**
     * 用户数量统计
     * @return
     */
    @GetMapping("/selectCount")
    public int count(){
        return userService.count();
    }

    /**
     * 添加用户
     * @param userInsertDTO
     * @return
     */
    @PostMapping("/add-new")
    @PreAuthorize("hasAuthority('/admin/add-new')")
    @LogAnnotation(module = 1,operator = "添加用户")
    public JsonResult<Void> addNew(UserInsertDTO userInsertDTO){
        userService.addNew(userInsertDTO);
        log.debug("添加成功");
        return JsonResult.ok();
    }
    /**
     * 获取修改列表数据
     * @param id
     * @return
     */
    @GetMapping("/selectById")
    public JsonResult<UserStandardVO> selectById(Integer id){
        UserStandardVO userStandardVO = mapper.selectById(id);
        return JsonResult.ok(userStandardVO);
    }

    /**
     * 个人中心信息
     * @param loginPrincipal
     * @return
     */
    @GetMapping("/selectInfo")
    public JsonResult<UserStandardVO> selectInfo(@AuthenticationPrincipal LoginPrincipal loginPrincipal){
        UserStandardVO userStandardVO = mapper.selectInfo(loginPrincipal.getId());
        return JsonResult.ok(userStandardVO);
    }

    /**
     * 修改用户信息
     * @param userUpdateDTO
     * @return
     */
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('/admin/update')")
    public JsonResult<Void> update(@Valid UserUpdateDTO userUpdateDTO){
        userService.updateUser(userUpdateDTO);
        return JsonResult.ok();
    }

    /**
     * 启用
     * @param id
     * @return
     */
    @PostMapping("/{id:[\\d]+}/enable")
    @PreAuthorize("hasAuthority('/admin/update')")
    @LogAnnotation(module = 1,operator = "启用账号")
    public JsonResult<Void> enable(@Range(min = 0) @PathVariable Integer id){
        userService.enable(id);
        return JsonResult.ok();
    }
    /**
     * 禁用
     * @param id
     * @return
     */
    @PostMapping("/{id:[\\d]+}/disable")
    @PreAuthorize("hasAuthority('/admin/update')")
    @LogAnnotation(module = 1,operator = "禁用账号")
    public JsonResult<Void> disable(@Range(min = 0) @PathVariable Integer id){
        userService.disable(id);
        return JsonResult.ok();
    }

    @GetMapping("/rebuild-cache")
    @LogAnnotation(module = 1,operator = "手动更新缓存")
    public JsonResult<Void> rebuildCache(){
        userService.rebuildUserCache();
        return JsonResult.ok();
    }

    @GetMapping("/currentUser")
    public JsonResult<UserStandardVO> currentUser(
            @AuthenticationPrincipal LoginPrincipal loginPrincipal){
        UserStandardVO userStandardVO = mapper.selectById(loginPrincipal.getId());
        log.debug("当前登录用户的信息:{}",loginPrincipal.getId());
        return JsonResult.ok(userStandardVO);
    }
}
